import { setDefaultHeader, getJSON, postJSON } from "./request";
import { ResponseStatus } from "./request";

export default {
  getToken() {
    return window.localStorage.getItem("token") || "";
  },
  setToken(token: string) {
    window.localStorage.setItem("token", token);
    setDefaultHeader("token", token);
  },

  async verifyToken() {
    const token = this.getToken();
    const result = await getJSON("/api/admin/verifyToken", {
      headers: {
        token,
      },
    });
    if (result.data) {
      this.setToken(token);
    }
    return result;
  },

  async login(username: string, password: string) {
    const result = await postJSON("/api/admin/login", {
      body: JSON.stringify({ username, password }),
    });
    if (result.status === ResponseStatus.SUCCESS) {
      // 保存 token
      this.setToken(result.data);
    }
    return result;
  },
};
